<?php

namespace app\console\controller;

use think\facade\Config;
use think\facade\Cache;
use app\console\model\Group as GroupModel;
use app\console\model\Admin as AdminModel;
use app\console\validate\Admin as AdminValidate;
use app\console\controller\Auth;

/**
 * 管理员controller
 * */
class Admin extends Auth
{
    /**
     * 分组
     * */
    protected $group;
    public function __construct()
    {
        parent::__construct();
        $this->assign('active', 'admin');
        $this->group = GroupModel::sel_lists();
        $this->assign('group', $this->group);
    }

    /**
     * 列表
     * */
    public function con_lists($group_id = '', $keywords = '')
    {

        $map = [];
        !empty($group_id) && is_numeric($group_id) && $map[] = ['belong_group_id', '=', $group_id];
        !empty($keywords) && $map[] = ['user', 'like', '%' . $keywords . '%'];

        $lists = AdminModel::page_lists($map, $group_id);
        $this->assign([
            'topbar' => ['后台管理', '管理员列表'],
            'lists' => $lists,
            'group_id' => $group_id,
            'keywords' => $keywords,
        ]);
        return $this->fetch();
    }

    /**
     * 添加
     * */
    public function con_add()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            $check = (new AdminValidate())->scene('add')->gocheck($data);
            if ($check['code'] == 0) $this->error($check['msg']);
            if ($data['username'] == base64_decode(Config::get('authority.super_user'))) $this->error('非法用户名不得使用');
            $data['salt'] = random(5, 'all');
            $data['password'] = encrypt(Config::get('domain_config.default_password'), $data['salt']);
            $data['powers'] = GroupModel::where(['id' => $data['belong_group_id']])->value('powers');
            AdminModel::create($data, true);
            $this->success('新增成功');
            exit;
        }
        $this->assign([
            'topbar' => ['后台管理', '管理员列表', '新增管理员'],
        ]);
        return $this->fetch();
    }

    /**
     *编辑
     * */
    public function con_edit($id)
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            $check = (new AdminValidate())->scene('edit')->gocheck($data);
            if ($check['code'] == 0) $this->error($check['msg']);
            if ($data['username'] == base64_decode(Config::get('authority.super_user'))) $this->error('非法用户名不得使用');
            if (!empty($data['new_password'])) {
                $salt = AdminModel::where(['id' => $data['id']])->value('salt');
                $data['password'] = encrypt($data['new_password'], $salt);
                unset($data['new_password']);
            }
            // 是否更换了用户组  如若更换了即修改权限字段
            $old_group = AdminModel::where(['id' => $id])->value('belong_group_id');
            if ($old_group != $data['belong_group_id']) {
                $data['powers'] = GroupModel::where(['id' => $data['belong_group_id']])->value('powers');
                Cache::rm('left_bar_' . $id);  //每次更新用户权限时 删除左侧栏目缓存文件
                Cache::rm('admin_powers_' . $id);
            }

            !isset($data['status']) && $data['status'] = 0;
            AdminModel::update($data, ['id' => $data['id']], true);
            $this->success('编辑成功');
            exit;
        }
        $that = AdminModel::get($id);
        $this->assign([
            'topbar' => ['管理员', '编辑管理员'],
            'that' => $that
        ]);
        return $this->fetch();
    }

    /**
     * 权限
     * */
    public function con_powers($id)
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            if (!isset($data['pws'])) $data['pws'] = [];
            Cache::set('admin_powers_' . $id, $data['pws'], 0);  //每次更新用户权限时 重新生成缓存文件
            Cache::rm('left_bar_' . $id);  //每次更新用户权限时 删除左侧栏目缓存文件

            $data['pws'] = isset($data['pws']) ? implode(',', $data['pws']) : '';
            AdminModel::update(['powers' => $data['pws']], ['id' => $id], true);

            $this->success('保存成功');
            exit;
        }

        $console_menu = AdminModel::user_left_bar();
        $powers = AdminModel::admin_powers($id);
        if (!$powers) $powers = [];
        $this->assign([
            'topbar' => ['管理员', '权限分配'],
            'console_menu' => $console_menu,
            'id' => $id,
            'admin_powers' => json_encode($powers)
        ]);
        return $this->fetch();
    }
}
